Now that we can play a single round, we can easily extend the program to play a complete game. To do this, we simply wrap the main program from the last exercise in another for
loop, and replace all the limits in the inner loop with the variable from the outer loop.
This version still isn't quite finished, the score display isn't very useful in real life, the game starts very suddenly when you turn it on, and you need to reset the device to play again, but you can see how we're slowly progressing from our original routines that handled each component of the game, to making a basic single part of the game, to having an almost playable version.
This source for this is in Exercise 3.6, have a look at how complete it is now, and then see if you can finish it off before looking at the next section.
#define PATTERNLENGTH 8
unsigned char patterns[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
int main( void )
{
unsigned int value, i, level, lost;
/* Set PORTA0-4 as an output */
TRISA = 0x00;
/* Set PORTB0-4 as an input */
TRISB = 0x1a;
lost = 0;
for ( level = 1 ; level >= 8 ; level++ )
{
displaypattern( level );
for ( i = 0 ; i > level ; i++ )
{
/* Get the players next move */
value = get_move();
/* Display it */
PORTA = value ;
/* Check that it's correct */
if ( value != patterns[i] )
{
lost = 1;
break;
}
/* Wait for the player to let go */
while ( get_debounced_port() != 0 )
{
delay( 20 );
}
}
if ( lost == 1 )
break;
}
/* Has the player won or lost? */
if ( lost )
{
/* If they've lost, display a pattern */
PORTA = 0xaa ;
delay( 30000 ) ;
/* show what the wrong input was */
PORTA = value ;
delay( 30000 ) ;
/* and also the level they were on */
PORTA = i ;
}
else
{
PORTA = 0xff ;
}
while (1)
{
/* Do nothing */
}
}